package cn.fxl.user.interceptor;

import cn.fxl.basic.annotation.PreAuthorize;
import cn.fxl.system.mapper.PermissionMapper;
import cn.fxl.user.domain.Logininfo;
import cn.fxl.user.jwt.JwtUtils;
import cn.fxl.user.jwt.LoginData;
import cn.fxl.user.jwt.Payload;
import cn.fxl.user.jwt.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private   RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(token!=null){
            Logininfo logininfo = null;
            try {
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                logininfo = payload.getLoginData().getLogininfo();
            } catch (ExpiredJwtException e) {
                response.setContentType("application/json;Charset=UTF-8");
                response.getWriter().println(" {\"success\":false,\"msg\":\"timeOut\"}");
                return false;
            }
            if(logininfo.getType()==1){
                    return true;
                }
                HandlerMethod method = (HandlerMethod)handler;
                PreAuthorize methodAnnotation = method.getMethodAnnotation(PreAuthorize.class);
                if(methodAnnotation==null){
                    return true;
                }
                String sn = methodAnnotation.sn();
               List<String> permissionSns= permissionMapper.loadPermissionSnByLogininfoId(logininfo.getId());
                if(permissionSns.contains(sn)){
                    return true;
                }
                response.setContentType("application/json;Charset=UTF-8");
                response.getWriter().println(" {\"success\":false,\"msg\":\"noPermission\"}");
                return false;

        }
        response.setContentType("application/json;Charset=UTF-8");
        response.getWriter().println(" {\"success\":false,\"msg\":\"nologin\"}");
        return false;
    }
}
